<template>
  <div class="mod-config">
    <el-form>
      <el-form-item>
        <el-button-group>
          <el-button size="mini" v-if="isAuth('purchase:purchaseplan:save')" type="primary"
            @click="addOrUpdateHandle()">新增</el-button>
          <el-button size="mini" v-if="isAuth('purchase:purchaseplan:delete')" type="danger" @click="deleteHandle()"
            :disabled="dataListSelections.length <= 0">删除</el-button>
        </el-button-group>
        <el-button-group>
          <el-button size="mini" v-if="isAuth('purchase:purchaseplan:export')" type="primary" @click="exportData()">导出
          </el-button>
          <el-button size="mini" v-if="isAuth('purchase:purchaseplan:export')" type="primary" @click="showAuditDialog()">审核
          </el-button>
          <!-- <el-button size="mini" v-if="isAuth('purchase:purchaseplan:import')" type="primary" @click="importData()">导入
          </el-button> -->
        </el-button-group>
      </el-form-item>
    </el-form>

    <el-divider></el-divider>

    <el-form :inline="true" :model="dataForm" ref="dataFormRef" @keyup.enter.native="getDataList()">
      <el-form-item>
        计划日期：
        <el-date-picker v-model="dataForm.queryDates" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" size="mini" @blur="getDataList()" clearable>
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        审批状态：
        <el-select size="mini" v-model="dataForm.isAudit" clearable placeholder="请选择" @change="getDataList()"
          @clear="getDataList()">
          <el-option value="1">审批通过</el-option>
          <el-option value="0">未审批</el-option>
          <el-option value="-1">不通过</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        主单过滤：
        <el-select size="mini" v-model="dataForm.queryField" clearable placeholder="请选择" @change="getDataList()"
          @clear="getDataList()">
          <el-option v-for="item in queryFields" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input size="mini" v-model="dataForm.key" placeholder="参数名" clearable @blur="getDataList()"
          @clear="getDataList()"></el-input>
      </el-form-item>

      <el-form-item>
        明细过滤：
        <el-select size="mini" v-model="dataForm.queryItemField" clearable placeholder="请选择" @change="getDataList()"
          @clear="getDataList()">
          <el-option v-for="item in queryItemFields" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input size="mini" v-model="dataForm.itemKey" placeholder="参数名" clearable @blur="getDataList()"
          @clear="getDataList()"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="getDataList()" size="mini" type="success">查询</el-button>
        <el-button @click="resetForm()" size="mini" type="info">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 主表 -->
    <el-table :data="dataList" border size="mini" v-loading="dataListLoading" @selection-change="selectionChangeHandle"
      height="320" style="width: 100%;" @row-click="tableRowClick" @cell-dblclick="tableDbEdit"
      :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
      <el-table-column type="selection" header-align="center" align="center" width="40">
      </el-table-column>
      <el-table-column type="index" width="50" header-align="center" align="center" label="#">
      </el-table-column>
      <el-table-column prop="planNo" width="220" header-align="center" sortable align="center" label="计划编号">
      </el-table-column>
      <el-table-column prop="planDate" header-align="center" align="center" sortable label="计划日期">
        <template slot-scope="scope">
          <el-date-picker type="date" v-model="scope.row.planDate" v-if="showInput == `planDate${scope.row.planId}`"
            value-format="yyyy-MM-dd" placeholder="选择日期" @blur='blurInput(scope.row, "planDate", scope.row.planDate)'
            v-focus>
          </el-date-picker>
          <span v-else style="text-decoration:none;"> {{scope.row.planDate | dateFormat}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="planTitle" header-align="center" align="center" label="计划标题">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.planTitle" v-if="showInput == `planTitle${scope.row.planId}`"
            @blur='blurInput(scope.row, "planTitle", scope.row.planTitle)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.planTitle}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="supplierName" header-align="center" align="center" label="供应商">
      </el-table-column>
      <el-table-column prop="totalAmount" header-align="center" align="center" label="总金额">
      </el-table-column>
      <el-table-column prop="makeUsername" header-align="center" align="center" label="制单人">
      </el-table-column>
      <el-table-column prop="auditStatus" header-align="center" align="center" label="审批状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.auditStatus == 1" type="success">已审批</el-tag>
          <el-tag v-else type="warning">未审批</el-tag>
          <el-tag v-if="scope.row.auditStatus == -1" type="danger">审批不通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="auditUsername" header-align="center" align="center" label="审批人">
      </el-table-column>
      <el-table-column prop="createTime" header-align="center" width="140" align="center" label="创建时间">
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.remark" v-if="showInput == `remark${scope.row.planId}`"
            @blur='blurInput(scope.row, "remark", scope.row.remark)' v-focus>
          </el-input>
          <span v-else v-html="scope.row.remark" style="text-decoration:none;"></span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="addOrUpdateHandle(scope.row.planId)">修改</el-button>
          <el-button size="mini" type="text" @click="deleteHandle(scope.row.planId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 子表 -->
    <el-table :data="itemDataList" border size="mini" class="item-table" height="250"
      @cell-dblclick="itemTableDbEdit" :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
      <el-table-column type="index" header-align="center" align="center" width="40" label="#">
      </el-table-column>
      <el-table-column prop="goodsCode" header-align="center" width="100" align="center" label="药品编码">
      </el-table-column>
      <el-table-column prop="goodsName" header-align="center" width="200" align="center" label="药品名称">
      </el-table-column>
      <el-table-column prop="stockNum" header-align="center" width="140" align="center" label="当前库存数量">
      </el-table-column>
      <el-table-column prop="purchaseNum" header-align="center" width="140" align="center" label="建议采购数量">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.purchaseNum" v-if="showItemInput == `purchaseNum${scope.row.itemId}`"
            @blur='blurItemInput(scope.row, "purchaseNum", scope.row.purchaseNum)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.purchaseNum}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="lastInPrice" header-align="center" width="100" align="center" label="上次进价">
      </el-table-column>
      <el-table-column prop="planInPrice" header-align="center" width="100" align="center" label="计划进价">
        <template slot-scope="scope">
          <el-input size="mini" v-model="scope.row.planInPrice" v-if="showItemInput == `planInPrice${scope.row.itemId}`"
            @blur='blurItemInput(scope.row, "planInPrice", scope.row.planInPrice)' v-focus>
          </el-input>
          <span v-else style="text-decoration:none;">{{scope.row.planInPrice}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="genericName" header-align="center" width="180" align="center" label="通用名称">
      </el-table-column>
      <el-table-column prop="standard" header-align="center" width="140" align="center" label="规格">
      </el-table-column>
      <el-table-column prop="unit" header-align="center" align="center" label="单位">
      </el-table-column>
      <el-table-column prop="producingArea" header-align="center" width="180" align="center" label="产地">
      </el-table-column>
      <el-table-column prop="produceFactory" header-align="center" width="200" align="center" label="生产单位">
      </el-table-column>
      <el-table-column prop="approvalNo" header-align="center" width="140" align="center" label="批准文号">
      </el-table-column>
      <el-table-column prop="dosageForm" header-align="center" width="160" align="center" label="剂型">
      </el-table-column>
      <el-table-column prop="barCode" header-align="center" align="center" label="条码">
      </el-table-column>
      <el-table-column prop="createTime" header-align="center" width="140" align="center" label="创建时间">
      </el-table-column>
      <el-table-column prop="updateTime" header-align="center" width="140" align="center" label="修改时间">
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注">
        <template slot-scope="scope">
          <span v-html="scope.row.remark"></span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" width="80" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="deleteItemHandle(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[5, 10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <!-- 审核 -->
    <dialog-audit v-if="auditVisible" ref="dialogAudit"></dialog-audit>
  </div>
</template>

<script>
  const _ = require("lodash")
  import AddOrUpdate from './purchaseplan-add-or-update'
  import DialogAudit from '@/views/components/dialog-audit'
  import {
    downLoadFile
  } from '@/utils/myUtil.js'
  export default {
    data() {
      return {
        dataForm: {
          queryDates:[],
          isAudit: undefined,
          key: '',
          queryField: '',
          itemKey: '',
          queryItemField: '',
        },
        queryFields: [],
        queryItemFields: [],
        dataList: [],
        itemDataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        auditVisible: false,
        showInput: "",
        showItemInput: "",
        oldData: {},
        oldItemData: {},
      }
    },
    components: {
      AddOrUpdate,
      DialogAudit
    },
    activated() {
      this.getDataList()
      this.initQueryParams()
    },
    methods: {
      // 获取数据列表
      async getDataList() {
        this.dataListLoading = true
        let newDataForm = _.cloneDeep(this.dataForm)
        let queryDates = newDataForm.queryDates || [];
        newDataForm.queryDates = queryDates.join(",")
        const res = await this.$http({
          url: `/purchase/purchaseplan/list`,
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'dataForm': newDataForm
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
          this.dataList.forEach(item => {
            item.status = item.status == 1 ? true : false
          })
          if (this.dataList.length > 0) {
            this.getItemDataList(this.dataList[0].planId)
          }else{
            this.itemDataList = []
          }
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      },
      async getItemDataList(planId) {
        const res = await this.$http({
          url: `/purchase/purchaseplanitem/listByPlanId`,
          method: 'get',
          params: this.$http.adornParams({
            planId
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          this.itemDataList = data.data
        } else {
          this.itemDataList = []
        }
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle(id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.planId
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await this.$http({
            url: `/purchase/purchaseplan/delete`,
            method: 'post',
            data: this.$http.adornData(ids, false)
          })
          let data = res.data
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      deleteItemHandle(row){
        this.$confirm(`确定对[itemId=${row.itemId}]进行[${row.itemId ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await this.$http({
            url: `/purchase/purchaseplanitem/delete`,
            method: 'post',
            data: this.$http.adornData([row.itemId], false)
          })
          let data = res.data
          if (data && data.code === 0) {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                //this.getItemDataList(row.planId)
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      resetForm() {
        this.$nextTick(() => {
          this.dataForm = this.$options.data().dataForm
          this.getDataList()
        })
      },
      async saveHandle(row, url) {
        row.status = row.status ? 1 : 0
        const res = await this.$http({
          url,
          method: 'post',
          data: this.$http.adornData(row)
        });
        let data = res.data
        if (data && data.code !== 0) {
          row.status = !row.status;
          return this.$message.error('修改失败!');
        }
        this.$message.success('更新成功！');
        this.getDataList();
      },
      // 当input失去光标后进行的操作
      blurInput(row, name, value) {
        // 判断数据是否有所改变，如果数据有改变则调用修改接口
        if (this.oldData[name] != value) {
          row[name] = value
          if (value === true) {
            row[name] = 1
          } else if (value === false) {
            row[name] = 0
          }
          this.saveHandle(row, `/purchase/purchaseplan/update`)
        }
        this.showInput = ""

      },
      blurItemInput(row, name, value) {
        // 判断数据是否有所改变，如果数据有改变则调用修改接口
        if (this.oldItemData[name] != value) {
          row[name] = value
          if (value === true) {
            row[name] =  1
          } else if (value === false) {
            row[name] = 0
          }
          this.saveHandle(row, `/purchase/purchaseplanitem/update`)
        }
        this.showItemInput = ""
      },
      tableDbEdit(row, column, cell, event) {
        this.showInput = column.property + row.planId;
        this.oldData[column.property] = row[column.property];
      },
      tableRowClick(row, column, event) {
        console.log("planId=", row.planId)
        this.getItemDataList(row.planId)
      },
      itemTableDbEdit(row, column, cell, event) {
        this.showItemInput = column.property + row.itemId;
        this.oldItemData[column.property] = row[column.property];
      },
      async exportData() {
        const res = await this.$http({
          url: `/purchase/purchaseplan/exportData`,
          method: 'get',
          responseType: 'blob',
          params: this.$http.adornParams()
        });
        downLoadFile(res)
      },
      showAuditDialog(){
        if(this.dataListSelections.length === 0){
          this.$message.warning("请选择要审核的单据！")
          return;
        }
        for(let item in this.dataListSelections){
          if(item.auditStatus === 1){
            this.$message.warning("请选择未审核的单据！")
            return;
          }
        }
        this.auditVisible = true
        this.$nextTick(() => {
          this.$refs.dialogAudit.init("采购计划")
        })
      },
      async audit(option){
        let ids = this.dataListSelections.map(item => {
          return item.planId
        })
        option.ids = ids.join(",")
        const res = await this.$http({
          url:`/purchase/purchaseplan/audit`,
          method: 'post',
          data: this.$http.adornData(option, false)
        })
        let data = res.data
        if (data && data.code === 0) {
            this.$message.success("审核成功！")
            this.getDataList()
        } else {
            this.$message.error(data.msg)
        }
      },
      initQueryParams() {

        let queryFields = [{
          value: 'plan_no',
          label: '计划编码'
        }, {
          value: 'plan_title',
          label: '计划标题'
        }, {
          value: 'supplier_name',
          label: '供应商'
        }, {
          value: 'make_username',
          label: '制单人'
        }, {
          value: 'audit_username',
          label: '审核人'
        }]

        let queryItemFields = [{
          value: 'goods_code',
          label: '编码'
        }, {
          value: 'bar_code',
          label: '条形码'
        }, {
          value: 'goods_name',
          label: '产品名称'
        }, {
          value: 'generic_name',
          label: '通用名'
        }, {
          value: 'producing_area',
          label: '产地'
        }, {
          value: 'produce_factory',
          label: '厂家'
        }, {
          value: 'dosage_form',
          label: '剂型'
        }, {
          value: 'standard',
          label: '规格'
        }, {
          value: 'approval_no',
          label: '批准文号'
        }]
        this.queryFields = queryFields;
        this.queryItemFields = queryItemFields;
      }
    },
    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      },
      focusTextarea: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "textarea") {
            el.focus()
          } else {
            if (el.getElementsByTagName("textarea")) {
              el.getElementsByTagName("textarea")[0].focus()
            }
          }
          el.focus()
        }
      }
    },
  }
</script>
<style lang="less" scoped>
  .item-table {
    margin-top: 15px;
  }

  .el-select {
    max-width: 100px;
  }

  .el-input {
    margin: 0px;
  }
</style>
